import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:imitatectripapp/dao/home_dao.dart';
import 'package:imitatectripapp/model/common_model.dart';
import 'package:imitatectripapp/model/grid_nav_model.dart';
import 'package:imitatectripapp/model/home_model.dart';
import 'package:imitatectripapp/model/sales_box_model.dart';
import 'package:imitatectripapp/pages/search_page.dart';
import 'package:imitatectripapp/widget/grid_nav.dart';
import 'package:imitatectripapp/widget/loacl_nav.dart';
import 'package:imitatectripapp/widget/loading_container.dart';
import 'package:imitatectripapp/widget/sales_box.dart';
import 'package:imitatectripapp/widget/search_bar.dart';
import 'package:imitatectripapp/widget/sub_nav.dart';
import 'package:imitatectripapp/widget/webview.dart';

// 默认显示的文字
const SEARCH_BAR_DEFAUL_TEXT = '网红打卡，景点，酒店，美食';
// 滚动的最大值
const APPBAR_SCROLL_OFFSET = 100;

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  // 自定义的appBar的透明度
  double appBarAlpha = 0;

  // 轮播图接口数据
  List<CommonModel> bannerList = [];

  // 球区接口数据
  List<CommonModel> localNavList = [];

  // 卡片接口数据
  GridNavModel gridNavModel;

  // 活动卡片接口数据
  List<CommonModel> subNavList = [];

  // 底部卡片接口数据
  SalesBoxModel salesBox;

  // 加载进度条变量
  bool _loading = true; //刚进入页面的时候需要进行网络加载，我们默认显示true
  @override
  void initState() {
    // TODO: implement initState
    // 页面初始化请求数据
    _loadData();
    super.initState();
  }

  // 监听列表的滚动
  void _Scroll(double pixels) {
    double alpha = pixels / APPBAR_SCROLL_OFFSET;
    if (alpha < 0) {
      alpha = 0;
    } else if (alpha > 1) {
      alpha = 1;
    }
    setState(() {
      appBarAlpha = alpha;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.grey[300],
        body: LoadingContainer(
          isLoading: _loading,
          child: Stack(
            children: <Widget>[
              MediaQuery.removePadding(
                removeTop: true,
                context: context,
                child: RefreshIndicator(
                    onRefresh: _loadData,
                    child: NotificationListener(
                      onNotification: (scrollNotification) {
                        if (scrollNotification is ScrollNotification &&
                            scrollNotification.depth == 0) {
                          //这里这个depth==0表示监听的是第一个元素
                          // 滚动且是列表的滚动的时候
                          _Scroll(scrollNotification.metrics.pixels);
                        }
                      },
                      child: _listView,
                    )),
              ),
              _appBar
            ],
          ),
        ));
  }

// 请求首页数据方法一
  // void _loadData() {
  //   HomeDao.fetch().then((result) {
  //     setState(() {
  //       resultString = json.encode(result);
  //     });
  //   }).catchError((onError) {
  //     setState(() {
  //       resultString = onError.toString();
  //     });
  //   });
  // }

  // 请求首页数据方法二
  Future<Null> _loadData() async {
    await Future.delayed(Duration(seconds: 2));
    try {
      HomeModel model = await HomeDao.fetch();
      setState(() {
        localNavList = model.localNavList;
        gridNavModel = model.gridNav;
        subNavList = model.subNavList;
        salesBox = model.salesBox;
        bannerList = model.bannerList;
      });
    } catch (e) {
      print(e);
    } finally {
      _loading = false;
    }
  }

  // 抽离的组件ListView
  Widget get _listView {
    return ListView(
      children: <Widget>[
        // 轮播图
        _banner,
        // 球区入口
        Padding(
          padding: EdgeInsets.fromLTRB(7, 4, 7, 4),
          child: LocalNav(localNavList: localNavList),
        ),
        // 卡片区域入口
        Padding(
          padding: EdgeInsets.fromLTRB(7, 0, 7, 4),
          child: GidNav(
            gridNavModel: gridNavModel,
          ),
        ),
        // 活动卡片的入口
        Padding(
          padding: EdgeInsets.fromLTRB(7, 0, 7, 4),
          child: SubNav(subNavList: subNavList),
        ),
        // 底部卡片入口
        Padding(
          padding: EdgeInsets.fromLTRB(7, 0, 7, 4),
          child: SalesBox(salesBox: salesBox),
        ),
      ],
    );
  }

  // 抽离组件appBar
  Widget get _appBar {
    return Column(
      children: <Widget>[
        Container(
          decoration: BoxDecoration(
              gradient: LinearGradient(
                  colors: [Color(0x66000000), Colors.transparent],
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter)),
          child: Container(
            padding: EdgeInsets.fromLTRB(0, 20, 0, 0),
            height: 115.0,
            decoration: BoxDecoration(
                color:
                    Color.fromARGB((appBarAlpha * 255).toInt(), 255, 255, 255)),
            child: SearchBar(
              searchBarType: appBarAlpha > 0.2
                  ? SearchBarType.homeLight
                  : SearchBarType.home,
              inputBoxClick: _jumpToSearch,
              speakClick: _jumpToSpeak,
              defaultText: SEARCH_BAR_DEFAUL_TEXT,
              leftButtonClick: () {},
            ),
          ),
        ),
        Container(
          height: appBarAlpha > 0.2 ? 0.5 : 0,
          decoration: BoxDecoration(
              boxShadow: [BoxShadow(color: Colors.black12, blurRadius: 0.5)]),
        )
      ],
    );
  }

  // 抽离组件轮播图banner
  Widget get _banner {
    return Container(
      height: 160,
      child: Swiper(
        itemCount: bannerList.length,
        autoplay: true,
        itemBuilder: (BuildContext context, int index) {
          return GestureDetector(
            onTap: () {
              Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) => WebView(
                            url: bannerList[index].url,
                            statusBarColor: bannerList[index].statusBarColor,
                            hideAppBar: bannerList[index].hideAppBar,
                          )));
            },
            child: Image.network(
              bannerList[index].icon,
              fit: BoxFit.fill,
            ),
          );
        },
        pagination: SwiperPagination(),
      ),
    );
  }

  // 跳转到搜索详情页
  void _jumpToSearch() {
    Navigator.push(context, MaterialPageRoute(builder: (context) {
      return SearchPage(hideLeft: false,hint: SEARCH_BAR_DEFAUL_TEXT,);
    }));
  }

  void _jumpToSpeak() {}
}
